<template>
  <div>
    <q-carousel
      v-model="slide"
      infinite
      transition-prev="scale"
      transition-next="scale"
      swipeable
      animated
      control-color="black"
      navigation
      padding
      arrows
    >
      <q-carousel-slide
        v-for="(item, index) in recommendCourses"
        :key="index"
        :name="'class' + index"
        class="flex flex-center"
      >
        <a class="full-height" style="width: 600px" :href="item.courseUrl">
          <q-img
            :src="imgUrlBase + item.courseImgUrl"
            height="100%"
            fit="contain"
          >
            <div class="absolute-bottom text-subtitle2 text-center">
              {{ item.courseName }}
            </div>
          </q-img>
        </a>
      </q-carousel-slide>
    </q-carousel>
    <q-separator></q-separator>
    <q-toolbar>
      <q-btn flat round dense icon="menu" class="q-mr-sm" />
      <q-toolbar-title>课程总览</q-toolbar-title>
      <q-input
        v-model="searchtext"
        standout="bg-primary text-white"
        dense
        class="q-ml-md col-8"
      >
        <template #append>
          <q-icon name="search" @click.prevent="courseSearch" />
          <q-icon
            v-if="searchtext !== ''"
            name="clear"
            class="cursor-pointer"
            @click="
              searchtext = '';
              searchDisplay = false;
            "
          />
        </template>
      </q-input>
    </q-toolbar>
    <div class="row justify-around items-center">
      <q-btn flat @click="majorturnpage(1)">
        <q-icon name="keyboard_arrow_left" size="md" />
      </q-btn>
      <q-option-group
        v-model="selectedmajor"
        :options="majorlistref"
        color="green"
        type="checkbox"
        class="row inline self-center"
      />
      <q-btn flat @click="majorturnpage(2)">
        <q-icon name="keyboard_arrow_right" size="md" />
      </q-btn>
    </div>
    <div v-if="searchDisplay">
      <h5>{{ searchtext }}的搜索结果</h5>
      <div v-if="searchTotal != 0" class="row q-col-gutter-lg q-px-md">
        <div
          v-for="(v, k) in seartResult"
          :key="k"
          class="col-3"
          transition="fade"
          once
        >
          <q-card>
            <a :href="v.courseUrl" target="_blank">
              <q-img :src="imgUrlBase + v.courseImgUrl">
                <div class="text-subtitle2 ellipsis absolute-bottom">
                  {{ v.courseName }}
                </div>
              </q-img>
            </a>
            <q-btn
              class="bg-white text-red"
              style="
                width: 20px;
                height: 20px;
                top: 0;
                right: 0;
                position: absolute;
                background: white;
              "
              :icon="
                favs.indexOf('a' + v.courseId.toString()) != -1
                  ? 'favorite'
                  : 'favorite_border'
              "
              @click.capture="addFavorite(v)"
            />

            <a :href="v.courseUrl" target="_blank">
              <q-card-section class="q-py-xs q-px-md">
                <p
                  class="ellipsis-2-lines text-body2 text-weight-thin q-ma-none"
                >
                  {{ v.courseDescription }}
                </p>
                <q-tooltip>{{ v.courseDescription }}</q-tooltip>
              </q-card-section>
              <!--之后后端添加后可替换 :icon="v.favorite ? 'favorite' : 'favorite_border'" -->
            </a>
          </q-card>
        </div>
      </div>
      <q-pagination
        v-if="searchTotal != 0"
        v-model="searchPage"
        class="absolute-bottom-center justify-center"
        :max="searchTotal"
        input
        @update:model-value="
          (v) => {
            // console.log(v, item, index + 1);
            getSearchResult(v);
          }
        "
      />
      <q-separator />
    </div>
    <div v-for="(item, index) in selectedmajor" :key="item">
      <div v-if="item in selectedmajor"></div>
      <h5>{{ majorlist[item] }} 专业课程</h5>
      <div v-if="coursetotal[item] != 0" class="row q-col-gutter-lg q-px-md">
        <div
          v-for="(v, k) in coursedata[item]"
          :key="k"
          class="col-3"
          transition="fade"
          once
        >
          <q-card>
            <a :href="v.majorCourseDTO.courseUrl" target="_blank">
              <q-img :src="imgUrlBase + v.majorCourseDTO.courseImgUrl">
                <div class="text-subtitle2 ellipsis absolute-bottom">
                  {{ v.majorCourseDTO.courseName }}
                </div>
              </q-img>
            </a>
            <q-btn
              class="bg-white text-red"
              style="
                width: 20px;
                height: 20px;
                top: 0;
                right: 0;
                position: absolute;
                background: white;
              "
              :icon="
                v.isFavorite ? 'favorite' : 'favorite_border'
                // favs.indexOf('a' + v.courseId.toString()) != -1
                //   ? 'favorite'
                //   : 'favorite_border'
              "
              @click.capture="addFavoriteNew(v)"
            />

            <a :href="v.majorCourseDTO.courseUrl" target="_blank">
              <q-card-section class="q-py-xs q-px-md">
                <p
                  class="ellipsis-2-lines text-body2 text-weight-thin q-ma-none"
                >
                  {{ v.majorCourseDTO.courseDescription }}
                </p>
                <q-tooltip>{{ v.majorCourseDTO.courseDescription }}</q-tooltip>
              </q-card-section>
              <!--之后后端添加后可替换 :icon="v.favorite ? 'favorite' : 'favorite_border'" -->
            </a>
          </q-card>
        </div>
      </div>
      <q-banner v-else>
        <span class="text-h6"> 该专业目前没有课程，看看别的？ </span>
      </q-banner>
      <q-pagination
        v-if="coursetotal[item] != 0"
        v-model="coursepage[item]"
        class="absolute-bottom-center justify-center"
        :max="coursetotal[item]"
        input
        @update:model-value="
          (v) => {
            // console.log(v, item, index + 1);
            getMajorCourse(v, item, index + 1);
          }
        "
      />
      <q-separator :key="item" />
    </div>
    <div class="text-center"><h4>下滑查看全部课程列表</h4></div>
    <!-- 无限滚动部分 -->
    <q-infinite-scroll
      v-if="true"
      id="scroll-target"
      ref="scroll"
      :initial-idex="1"
      :offset="500"
      :debounce="1000"
      scroll-target="#scroll-target"
      class="row q-col-gutter-lg q-px-md q-mt-md"
      @load="loadMoreData"
    >
      <q-intersection
        v-for="(item, index) in allCourseData"
        :key="index"
        class="course col-3"
        transition="fade"
        once
      >
        <q-card class="full-height">
          <a :href="item.courseUrl" target="_blank">
            <q-img :src="imgUrlBase + item.courseImgUrl">
              <div class="text-subtitle2 ellipsis absolute-bottom">
                {{ item.courseName }}
              </div>
            </q-img>
          </a>
          <q-btn
            class="bg-white text-red"
            style="
              width: 20px;
              height: 20px;
              top: 0;
              right: 0;
              position: absolute;
              background: white;
            "
            :icon="
              favs.indexOf('a' + item.courseId.toString()) != -1
                ? 'favorite'
                : 'favorite_border'
            "
            @click.capture="addFavorite(item)"
          />

          <a :href="item.courseUrl" target="_blank">
            <q-card-section class="q-py-xs q-px-md">
              <p class="ellipsis-2-lines text-body2 text-weight-thin q-ma-none">
                {{ item.courseDescription }}
              </p>
              <q-tooltip>{{ item.courseDescription }}</q-tooltip>
            </q-card-section>
            <!--之后后端添加后可替换 :icon="v.favorite ? 'favorite' : 'favorite_border'" -->
          </a>
        </q-card>
        <!-- <my-course :item="item" :add-favorite="addFavorite" /> -->
      </q-intersection>
      <template #loading>
        <div class="row justify-center q-my-md" style="width: 100%">
          <q-spinner-dots color="primary" size="40px" />
        </div>
      </template>
      <div v-if="showNotice" class="row justify-center" style="width: 100%">
        已经到底了！
      </div>
    </q-infinite-scroll>
  </div>
</template>
<script setup>
import { onMounted, ref } from "vue";
import { baseurl, imgUrlBase } from "src/js/global";
import { get, post } from "src/js/fetch";
import { useQuasar } from "quasar";
import { majorlist as majorlisttestdata } from "src/js/majorlist";
const logged = defineModel({ type: String, default: "false" });
function getUserDetail() {
  let majorid = -1;
  const url = baseurl + "user/detail";
  post(url, null).then((res) => {
    if (res.success) {
      if (res.data.majorid) {
        majorid = res.data.majorid;
        const url = new URL(baseurl + "course/list/" + majorid);
        get(url).then((res) => {
          if (res.success) {
            recommendCourses.value = res.data;
          }
        });
      }
    }
  });
}
const allCourseData = ref([]);
const scroll = ref();
const showNotice = ref(false);
async function loadMoreData(index, done) {
  const url = new URL(baseurl + "course/listAll");
  url.searchParams.set("current", index);
  url.searchParams.set("size", 8);
  let result = await get(url);
  // console.log(result);
  if (result.error || !result.success) {
    showNotice.value = true;
    scroll.value.stop();
  } else {
    allCourseData.value = allCourseData.value.concat(result.data);
    done();
  }
}
const recommendCourses = ref([]);
function courseRecommend() {
  console.log("majorid", userMajor.value);
  if (userMajor.value != "") {
    const url = new URL(baseurl + "course/list/" + userMajor.value);
    get(url).then((res) => {
      recommendCourses.value = res.data.slice(0, 4);
    });
  } else {
    const url = new URL(baseurl + "course/listAll");
    url.searchParams.set("current", 1);
    url.searchParams.set("size", 4);
    get(url).then((res) => {
      recommendCourses.value = res.data;
    });
  }
  // console.log(recommendCourses.value);
}

const userMajor = ref("");
function checkMajorFilled() {
  const url = new URL(baseurl + "user/detail");
  post(url).then((res) => {
    if (res.success) {
      userMajor.value = res.data.majorId;
    }
    courseRecommend();
  });
}

onMounted(() => {
  checkMajorFilled();
  getMajorList();
  // loadMoreData(1, () => {});
  getFavCourse();
  getUserDetail();
  window.addEventListener("scroll", handleScroll, true);
});

const coursedata = ref({});
const coursepage = ref([]);
const coursetotal = ref({});
function getMajorCourse(value, majorid, majorindex) {
  const url = new URL(baseurl + "course/listPage/" + majorid);
  url.searchParams.set("current", value);
  url.searchParams.set("size", 4);
  get(url).then((res) => {
    // console.log(res);
    // console.log(value, majorid, majorindex, res);
    if (res.success) {
      coursedata.value[majorid] = res.data;
      coursetotal.value[majorid] = res.totalPage;
    }
    // console.log(coursedata.value);
  });
}
function getAllCourse() {
  // console.log(majorlist, totalmajor);
  Object.keys(majorlist).forEach((v, i) => {
    getMajorCourse(1, v, i);
  });
}

const selectedmajor = ref([]);
const majorlistref = ref([]);
let majorlist = {};
let majorpage = 0;
let totalmajor = 0;
async function getMajorList() {
  const url = new URL(baseurl + "major/list");
  await get(url).then((res) => {
    // console.log(res);
    res.data.forEach((v) => {
      majorlist[v.id.toString()] = v.name;
      coursepage.value[v.id.toString()] = 1;
      coursetotal.value[v.id.toString()] = 0;
      coursedata.value[v.id.toString()] = [];
      selectedmajor.value.push(v.id.toString());
      // console.log("aa", selectedmajor.value);
    });
    totalmajor = Object.keys(majorlist).length;
    const tar = Object.entries(majorlist).slice(
      majorpage * 10,
      majorpage * 10 + 10
    );
    // console.log("tar", tar);
    majorlistref.value = [];
    tar.forEach((v) => {
      majorlistref.value.push({ label: v[1], value: v[0] });
    });
    // console.log("ee", majorlistref.value);
    getAllCourse();
  });
}
function testMajorList() {
  majorlisttestdata.value.forEach((v) => {
    majorlist.push({ label: v.name, value: v.id });
    coursepage.value[v.id.toString()] = 1;
    coursetotal.value[v.id.toString()] = 0;
    coursedata.value[v.id.toString()] = [];
    selectedmajor.value.push(v.id);
  });
  totalmajor = Object.keys(majorlist).length;
  const tar = Object.entries(majorlist).slice(
    majorpage * 10,
    majorpage * 10 + 10
  );
  majorlistref.value = [];
  tar.forEach((v) => {
    majorlistref.value.push({ label: v[0], value: v[1] });
  });
}
function majorturnpage(c) {
  if (c == 2 && (majorpage + 1) * 10 <= totalmajor) {
    majorpage++;
    const tar = Object.entries(majorlist).slice(
      majorpage * 10,
      majorpage * 10 + 10
    );
    majorlistref.value = [];
    tar.forEach((v) => {
      majorlistref.value.push({ label: v[1], value: v[0] });
    });
  } else if (c == 1 && (majorpage - 1) * 10 >= 0) {
    majorpage--;
    const tar = Object.entries(majorlist).slice(
      majorpage * 10,
      majorpage * 10 + 10
    );
    majorlistref.value = [];
    tar.forEach((v) => {
      majorlistref.value.push({ label: v[1], value: v[0] });
    });
  }
}
const slide = ref("class1");
const $q = useQuasar();
function addFavorite(item) {
  // item.favorite = !item.favorite;
  favs.value = favs.value.filter((v) => v !== item.courseId);
  const url = new URL(baseurl + "course/favorite");
  url.searchParams.set("courseId", item.courseId);
  post(url).then((res) => {
    $q.notify({
      message: res.data,
      type: "positive",
      position: "center",
    });
  });
}

function addFavoriteNew(item) {
  item.isFavorite = !item.isFavorite;
  favs.value = favs.value.filter((v) => v !== item.majorCourseDTO.courseId);
  const url = new URL(baseurl + "course/favorite");
  url.searchParams.set("courseId", item.majorCourseDTO.courseId);
  post(url).then((res) => {
    $q.notify({
      message: res.data,
      type: "positive",
      position: "center",
    });
  });
}

const searchtext = ref("");
const seartResult = ref([]);
const searchPage = ref(1);
const searchTotal = ref(1);
const searchDisplay = ref(false);
function courseSearch() {
  getSearchResult(1);
}
function getSearchResult(index) {
  const url = new URL(baseurl + "course/name/" + searchtext.value);
  url.searchParams.set("current", index);
  url.searchParams.set("size", 4);
  get(url).then((res) => {
    if (res.success) {
      searchDisplay.value = true;
      seartResult.value = res.data;
      searchTotal.value = res.totalPage;
    } else {
      $q.notify({
        message: res.errorMsg,
        type: "warning",
        position: "center",
      });
    }
  });
}
const scrollend = ref(false);
function handleScroll(e) {
  if (e.target.scrollTop + e.target.clientHeight >= e.target.scrollHeight) {
    scrollend.value = true;
  }
}
const favs = ref([]);
function getFavCourse() {
  const url = new URL(baseurl + "user/favorites");
  url.searchParams.set("current", 1);
  url.searchParams.set("size", 100);
  get(url).then((res) => {
    // console.log(res);
    if (res.success) {
      res.data.forEach((v) => {
        favs.value.push("a" + v.id.toString());
      });
      // console.log(favs.value);
    }
  });
}
</script>
<style scoped>
a {
  text-decoration: none;
  color: black;
}
</style>
